import React, { useState } from 'react';
import { useDispatch } from 'react-redux';
import { useSelector } from 'react-redux';
import { addActionCreator, delByIdActionCreator, updateActionCreator } from './store/action/todo';
import './styles/base.css';
import './styles/index.css';

export default function App() {
  return (
    <section className="todoapp">
      <Header></Header>
      <Main></Main>
      <Footer></Footer>
    </section>
  );
}
function Footer() {
  return (
    <footer className="footer">
      <span className="todo-count">
        <strong>1</strong> 剩余
      </span>
      <ul className="filters">
        <li>
          <a className="all selected" href="#/">
            全部
          </a>
        </li>
        <li>
          <a className="active" href="#/active">
            未完成
          </a>
        </li>
        <li>
          <a className="completed" href="#/completed">
            已完成
          </a>
        </li>
      </ul>
      <button className="clear-completed">清除已完成</button>
    </footer>
  );
}

function Main() {
  // 4. 按模块名取出使用
  const { list } = useSelector((state) => state.todo);

  const dispatch = useDispatch();

  return (
    <section className="main">
      <input id="toggle-all" className="toggle-all" type="checkbox" />
      <label htmlFor="toggle-all">全选</label>
      <ul className="todo-list">
        {list.map((item) => (
          <li className={item.isDone ? 'completed' : ''} key={item.id}>
            <div className="view">
              <input
                className="toggle"
                type="checkbox"
                checked={item.isDone}
                onChange={() => dispatch(updateActionCreator(item.id))}
              />
              <label>{item.task}</label>
              <button
                className="destroy"
                onClick={() => dispatch(delByIdActionCreator(item.id))}
              ></button>
            </div>
          </li>
        ))}
      </ul>
    </section>
  );
}

function Header() {
  const [task, setTask] = useState('');
  const dispatch = useDispatch();

  const handleKeyDown = (e) => {
    if (e.keyCode === 13) {
      console.log('回车触发了  ----->  ');
      dispatch(addActionCreator({ id: Date.now(), task, isDone: false }));
      setTask('');
    }
  };

  return (
    <header className="header">
      <h1>todos</h1>
      <input
        className="new-todo"
        placeholder="需要做什么"
        autoFocus
        value={task}
        onChange={(e) => setTask(e.target.value)}
        onKeyDown={handleKeyDown}
      />
    </header>
  );
}
